package com.lagou.edu.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.lagou.edu.pojo.Bill;
import com.lagou.edu.pojo.BillDetail;
import com.lagou.edu.service.BillDetailService;
import com.lagou.edu.service.BillService;
import com.lagou.edu.util.BillNumUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/bill")
public class BillController {

    /**
     * Spring容器和SpringMVC容器是有层次的（父子容器）
     * Spring容器：service对象+dao对象
     * SpringMVC容器：controller对象，，，，可以引用到Spring容器中的对象
     */
    private BillNumUtil billNumUtil = BillNumUtil.getInstance();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final double personMostBillPrice=30d;
    @Autowired
    private BillService billService;
    @Autowired
    private BillDetailService billDetailService;

    /**
     * 增加发票单以及发票详情数据
     *
     * @param bill
     * @return
     * @throws Exception
     */
    @RequestMapping("/addBill")
    @ResponseBody
    public String addBill(Bill bill) throws Exception {
        Map map = new HashMap<>();
        String nowDate = sdf.format(new Date());
        //单号
        String billNum = billNumUtil.getBillNum();
        bill.setBillNum(billNum);
        bill.setMealTime(changeDateFormat(bill.getMealTime()));
        //更新时间
        bill.setUpdateTime(nowDate);
        //计算人数
        int personNum = bill.getPersonNum();
        String[] personNames = bill.getMealPersons().split("，");
        if (personNum == personNames.length) {
            for (String personName : personNames) {
                BillDetail billDetail = new BillDetail();
                billDetail.setDetailNum(billNumUtil.getBillDetailNum());
                billDetail.setBillNum(billNum);
                billDetail.setPersonName(personName);
                billDetail.setUpdateTime(nowDate);
                billDetail.setQuitTime("00:00");
                //单人报销，付款金额自动赋值，报销金额
                if (personNames.length == 1) {
                    //个人付款金额
                    billDetail.setPersonPayPrice(bill.getPayAllPrice());
                    //个人报销数额
                    if(bill.getReimbursementPrice()>=personMostBillPrice){
                        billDetail.setBillPrice(personMostBillPrice);
                    }else{
                        billDetail.setBillPrice(bill.getReimbursementPrice());
                    }
                }
                //保存发票详情
                billDetailService.addBillDetail(billDetail);
            }
            //保存发票
            billService.addBill(bill);
        }
        map.put("url", "/jsp/index.jsp"); //返回的文件名
        map.put("result", "success");
        return new Gson().toJson(map);
    }

    /**
     * 发票详情
     * @param billNum
     * @return
     */
    @RequestMapping("/queryBillDetail")
    @ResponseBody
    public String queryBillDetail(String billNum) {
        List<BillDetail> billDetails = billDetailService.queryBillDetail(billNum);
        double personPayPrice_sum = 0.0;
        double billPrice_sum = 0.0;
        for (BillDetail billDetail : billDetails) {
            personPayPrice_sum += billDetail.getPersonPayPrice();
            billPrice_sum += billDetail.getBillPrice();
        }
        Map<String, String> totalRowMap = new HashMap<>();
        totalRowMap.put("personPayPrice", Double.toString(personPayPrice_sum));
        totalRowMap.put("billPrice", Double.toString(billPrice_sum));

        //该发票应发放金额
        //Bill bill = billService.queryBill(billNum);

        Map<String, Object> retMap = new HashMap<>();
        retMap.put("code", "0");
        retMap.put("msg", "");
        retMap.put("count", billDetails.size());
        retMap.put("data", billDetails);
        retMap.put("totalRow", totalRowMap);
        //retMap.put("shouldGiveOutMoney",bill.getReimbursementPrice());
        Gson gson = new Gson();
        String result = gson.toJson(retMap);
        return result;
    }

    /**
     * 列表页查询
     * @return
     */
    @RequestMapping("/queryBillList")
    @ResponseBody
    public String queryBillList(@RequestParam(value = "page", defaultValue = "1") int page,
                                @RequestParam(value = "limit", defaultValue = "10") int limit,
                                @RequestParam(value = "mealTime", defaultValue = "") String mealTime,
                                @RequestParam(value = "mealPersons", defaultValue = "") String mealPersons,
                                @RequestParam(value = "billAllPrice", defaultValue = "0.0") double billAllPrice,
                                @RequestParam(value = "payer", defaultValue = "") String payer) {
        //日期转换
        if (StringUtils.isNotEmpty(mealTime)){
            mealTime=changeDateFormat(mealTime);
        }
        /*if (StringUtils.isNotEmpty(mealTime) && mealTime.split("-").length == 3) {
            String[] split = mealTime.split("-");
            mealTime = split[0] + "年" + split[1] + "月" + split[2] + "日";
        }*/
        //根据查询条件查询
        Map<String, Object> searchMap = new HashMap<>();
        searchMap.put("mealTime", mealTime);
        searchMap.put("mealPersons", mealPersons);
        searchMap.put("billAllPrice", billAllPrice);
        searchMap.put("payer", payer);

        //查询结果分页
        Page page1 = PageHelper.startPage(page, limit);
        List<Bill> bills = billService.queryBillList(searchMap);

        //查询结果总数
        int count = (int) page1.getTotal();

        //报销总金额
        double reimbursementPrice_sum=0.0d;
        //付款总金额
        double payAllPrice_sum=0.0d;
        //发票总金额
        double billAllPrice_sum=0.0d;
        for(Bill bill:bills){
            reimbursementPrice_sum+=bill.getReimbursementPrice();
            payAllPrice_sum+=bill.getPayAllPrice();
            billAllPrice_sum+=bill.getBillAllPrice();
        }

        Map<String, String> totalRowMap = new HashMap<>();
        totalRowMap.put("reimbursementPrice", Double.toString(reimbursementPrice_sum));
        totalRowMap.put("payAllPrice", Double.toString(payAllPrice_sum));
        totalRowMap.put("billAllPrice", Double.toString(billAllPrice_sum));

        //返回信息
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("code", "0");
        retMap.put("msg", "");
        retMap.put("count", count);
        retMap.put("data", bills);
        retMap.put("totalRow", totalRowMap);
        Gson gson = new Gson();
        String result = gson.toJson(retMap);
        return result;
    }

    /**
     * 删除发票明细
     * @param detailNum
     * @return
     */
    @RequestMapping("/deleteBillDetail")
    @ResponseBody
    public String deleteBillDeail(String detailNum) {
        billDetailService.deleteBillDetail("", detailNum);
        return "success";
    }
    //删除发票
    @RequestMapping("/deleteBill")
    @ResponseBody
    public String deleteBill(String billNum) {
        billDetailService.deleteBillDetail(billNum, "");
        billService.deleteBill(billNum);
        return "success";
    }
    //更新发票明细
    @RequestMapping("/updateBillDetail")
    @ResponseBody
    public String deleteBillDeail(String detailNum, String quitTime, String billPrice,String personPayPrice) {
        HashMap<String, String> map = new HashMap<>();
        map.put("detailNum", detailNum);
        map.put("quitTime", quitTime);
        map.put("billPrice", billPrice);
        map.put("personPayPrice", personPayPrice);
        map.put("updateTime", sdf.format(new Date()));
        billDetailService.updateBillDeail(map);
        return "success";
    }


    //格式化日期
    public String changeDateFormat(String time) {
        if (StringUtils.isEmpty(time)) {
            return "";
        }
        String[] split = time.split("-");
        if (split.length == 3) {
            return split[0] + "年" + split[1] + "月" + split[2] + "日";
        } else {
            return "";
        }
    }

}
